package com.vankimgps.activity;

import com.vankimgps.constant.Constant;
import com.vankimgps.database.DatabaseHelper;
import com.vankimgps.models.ResponseLogin;
import com.vankimgps.services.ServiceListener;
import com.vankimgps.services.Services;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity implements
ServiceListener {
	private EditText txtUsername;
	private EditText txtPassword;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_layout);

		txtUsername = (EditText)findViewById(R.id.txtUsername);
		txtPassword = (EditText)findViewById(R.id.txtPassword);				
		
		DatabaseHelper dt = new DatabaseHelper(this);
		txtUsername.setText(dt.getUserName());
		txtPassword.setText(dt.getPassword());
				
		Button btnLogin = (Button)findViewById(R.id.btnLogin);

		btnLogin.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				login(txtUsername.getText().toString(), txtPassword.getText().toString());
			}
		});
	}
	
	void login(String Username, String Password){
		Services service = new Services(this);
		service.login(Username, Password);
	}
	
	@Override
	public void onCompleted(Services service, Object result) {

		ResponseLogin response = (ResponseLogin)result;
		
		int Code = response.getCode();

		if (Code == Constant.CODE_OK){
			DatabaseHelper dt = new DatabaseHelper(this);
			dt.setUserInfo(response.getUserInfo());			
			dt.setLogin(true);
			
			dt.setUserName(txtUsername.getText().toString());
			dt.setPassword(txtPassword.getText().toString());
			
			// open Tabhost
			Intent intent = new Intent(this,TrackingActivity.class);	
			startActivity(intent);
			finish();
		}else{
			AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
			alertBuilder.setTitle(R.string.alert_title);
			switch (Code) {
				case  Constant.CODE_ERROR_MISSING_PASSWORD:
					alertBuilder.setMessage(R.string.msg_missing_password);
					break;
				case Constant.CODE_ERROR_MISSING_USERNAME:
					alertBuilder.setMessage(R.string.msg_missing_username);
					break;
				default:
					alertBuilder.setMessage(R.string.msg_can_not_login);	
					break;
			}

			alertBuilder.setCancelable(false);
			alertBuilder.setNegativeButton(R.string.alert_button_ok, null);
			AlertDialog alert = alertBuilder.create();
			alert.show();
		}
	}
}